package snow

import (
	"time"

	jwt "github.com/dgrijalva/jwt-go"
)

const TokenExpireDuration = time.Hour

var MySecret = []byte("夏天很热")

type MyClaims struct {
	UserId   int64  `json: "user_id"`
	UserName string `json: "username"`
	jwt.StandardClaims
}

// 生成JWT Token
func GenerateToken(UserId int64, username string) (string, error) {
	claims := MyClaims{
		UserId:   UserId,
		UserName: username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(TokenExpireDuration * time.Duration(24*365)).Unix(), //过期时间
			Issuer:    "bluebell",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return tokenClaims.SignedString(MySecret)
}

// 解析JWT Token
func ParseToken(token string) (*MyClaims, error) {
	var mc = new(MyClaims)
	tokenClaims, err := jwt.ParseWithClaims(token, mc, func(token *jwt.Token) (interface{}, error) {
		return MySecret, nil
	})

	if err != nil {
		return nil, err
	}

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*MyClaims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
